/**
 * API服务类 - 对接后端接口
 * 基于聚点美食API接口文档实现
 */

const { getConfig } = require('./config.js');

class ApiService {
  constructor() {
    // 基础配置
    const config = getConfig();
    this.baseURL = config.apiBaseUrl;
    this.wsUrl = config.wsUrl;
    this.timeout = 10000; // 请求超时时间
    this.debug = config.debug;
    // 移除内存中的token，只使用存储中的token
    
    
    // 错误码映射 - 根据API文档v1.3.0更新
    this.errorMessages = {
      10001: '房间不存在',
      10002: '房间已关闭',
      10003: '房间已过期',
      10004: '无权限访问房间',
      10005: '您已在此房间中',
      10006: '房间人数已达上限',
      20001: '您已在此房间中提交过订单',
      20002: '订单不存在',
      20003: '无权限操作订单',
      20004: '订单状态不允许操作',
      20005: '菜品不存在',
      20006: '菜品不可用',
      40001: '微信授权失败',
      40002: '用户已被禁用',
      50001: '创建房间失败',
      50002: '提交订单失败',
      50003: '登录失败，请重试'
    };

    // HTTP状态码与业务错误码的映射关系
    this.statusCodeMapping = {
      400: [10002, 10003, 10005, 10006, 20001, 20004, 20006, 40001], // 业务规则限制
      403: [10004, 20003, 40002], // 权限不足
      404: [10001, 20002, 20005], // 资源不存在
      409: [20001], // 资源冲突（重复提交订单）
      500: [50001, 50002, 50003] // 服务器错误
    };
  }

  /**
   * 统一请求方法
   * @param {Object} options 请求配置
   * @returns {Promise} 请求结果
   */
  request(options) {
    return new Promise((resolve, reject) => {
      let loadingShown = false;
      
      // 显示加载提示
      if (options.showLoading !== false) {
        wx.showLoading({
          title: '加载中...',
          mask: true
        });
        loadingShown = true;
      }

      // 构建完整URL
      const fullUrl = this.baseURL + options.url;
      
      // console.log('发送网络请求:', {
      //   url: fullUrl,
      //   method: options.method || 'GET',
      //   data: options.data || {},
      //   headers: {
      //     'Content-Type': 'application/json',
      //     'Authorization': this.token ? `Bearer ${this.token}` : '',
      //     ...options.header
      //   },
      //   timeout: this.timeout
      // });

      // console.log('进入网络');
      
      wx.request({
        url: fullUrl,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Content-Type': 'application/json',
          'Authorization': this.getToken() ? `Bearer ${this.getToken()}` : '',
          ...options.header
        },
        timeout: this.timeout,
        // 微信小程序特殊配置
        enableHttp2: false,
        enableQuic: false,
        enableCache: false,
        enableChunked: false,
        success: (res) => {
          // console.log(res);
          // 隐藏加载提示
          if (loadingShown) {
            wx.hideLoading();
            loadingShown = false;
          }
          // 处理响应
          if (res.statusCode >= 200 && res.statusCode < 300) {
            // 成功响应
            if (res.data.code === 200 || res.data.code === 201) {
              resolve(res.data);
            } else {
              // 业务错误
              this.handleBusinessError(res.data);
              reject(res.data);
            }
          } else {
            // HTTP错误
            this.handleHttpError(res);
            reject(res);
          }
        },
        fail: (error) => {
          // console.log(error);
          // 隐藏加载提示
          if (loadingShown) {
            wx.hideLoading();
            loadingShown = false;
          }
          
          
          this.handleNetworkError(error);
          reject(error);
        }
      });
    });
  }

  /**
   * 处理业务错误
   * @param {Object} error 错误信息
   */
  handleBusinessError(error) {
    const message = this.errorMessages[error.code] || error.message || '操作失败';
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  }

  /**
   * 处理HTTP错误
   * @param {Object} res 响应对象
   */
  handleHttpError(res) {
    let message = '请求失败';
    let showToast = true;
    
    // 检查是否是业务错误（即使HTTP状态码不是2xx，但包含业务错误信息）
    if (res.data && res.data.code && typeof res.data.code === 'number') {
      // 这是业务错误，使用业务错误处理
      this.handleBusinessError(res.data);
      return;
    }
    
    switch (res.statusCode) {
      case 400:
        message = '请求参数错误';
        break;
      case 401:
        message = '未授权，请重新登录';
        this.clearAuth();
        break;
      case 403:
        message = '禁止访问';
        break;
      case 404:
        message = '请求的资源不存在';
        break;
      case 409:
        message = '资源冲突';
        break;
      case 422:
        message = '数据验证失败';
        break;
      case 500:
        // 500错误通常是后端接口未实现，显示Toast
        message = '服务器内部错误，请稍后重试';
        showToast = true;
        break;
      case 503:
        message = '服务暂时不可用';
        break;
      default:
        message = `请求失败 (${res.statusCode})`;
    }
    
    if (showToast) {
      wx.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      });
    }
  }

  /**
   * 处理网络错误
   * @param {Object} error 错误信息
   */
  handleNetworkError(error) {
    let message = '网络连接失败';
    
    if (error.errMsg) {
      if (error.errMsg.includes('timeout')) {
        message = '请求超时，请检查网络连接';
      } else if (error.errMsg.includes('fail')) {
        message = '网络连接失败，请检查网络设置';
      }
    }
    
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  }

  /**
   * 清除认证信息
   */
  clearAuth() {
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    
    // 跳转到登录页面
    wx.reLaunch({
      url: '/pages/index/index'
    });
  }

  /**
   * 设置Token
   * @param {String} token 认证令牌
   */
  setToken(token) {
    wx.setStorageSync('token', token);
  }

  /**
   * 获取Token
   * @returns {String} 认证令牌
   */
  getToken() {
    return wx.getStorageSync('token') || '';
  }

  // ==================== 用户认证接口 ====================

  /**
   * 微信小程序登录
   * @param {String} code 微信授权码
   * @param {Object} userInfo 用户信息
   * @returns {Promise} 登录结果
   */
  async login(code, userInfo) {
    try {
      const response = await this.request({
        url: '/auth/login',
        method: 'POST',
        data: {
          code: code,
          userInfo: userInfo
        },
        showLoading: false
      });

      // 保存认证信息
      if (response.data && response.data.token) {
        this.setToken(response.data.token);
        if (response.data.user) {
          wx.setStorageSync('userInfo', response.data.user);
        }
      }

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取当前用户信息
   * @returns {Promise} 用户信息
   */
  async getCurrentUser() {
    try {
      const response = await this.request({
        url: '/auth/me',
        method: 'GET'
      });

      return response.data.user;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 刷新Token
   * @returns {Promise} 新的Token
   */
  async refreshToken() {
    try {
      const response = await this.request({
        url: '/auth/refresh',
        method: 'POST'
      });

      if (response.data && response.data.token) {
        this.setToken(response.data.token);
      }

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 退出登录
   * @returns {Promise} 退出结果
   */
  async logout() {
    try {
      const response = await this.request({
        url: '/auth/logout',
        method: 'POST'
      });

      // 清除本地认证信息
      this.clearAuth();

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  // ==================== 房间管理接口 ====================

  /**
   * 创建房间
   * @param {Object} roomData 房间数据
   * @returns {Promise} 房间信息
   */
  async createRoom(roomData) {
    try {
      const response = await this.request({
        url: '/rooms',
        method: 'POST',
        data: roomData
      });

      return response.data.room;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 加入房间
   * @param {String} roomId 房间ID
   * @returns {Promise} 房间信息
   */
  async joinRoom(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/join`,
        method: 'POST'
      });

      return response.data.room;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取房间信息
   * @param {String} roomId 房间ID
   * @returns {Promise} 房间信息
   */
  async getRoomInfo(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}`,
        method: 'GET'
      });

      return response.data.room;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户房间列表
   * @param {Object} params 查询参数
   * @returns {Promise} 房间列表
   */
  async getMyRooms(params = {}) {
    try {
      const response = await this.request({
        url: '/rooms/my',
        method: 'GET',
        data: params
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取最近房间
   * @param {Object} params 查询参数
   * @returns {Promise} 最近房间列表
   */
  async getRecentRooms(params = {}) {
    try {
      const response = await this.request({
        url: '/rooms/recent',
        method: 'GET',
        data: params
      });

      return response.data.rooms;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取置顶房间
   * @returns {Promise} 置顶房间列表
   */
  async getPinnedRooms() {
    try {
      const response = await this.request({
        url: '/rooms/pinned',
        method: 'GET'
      });

      return response.data.rooms;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 设置房间置顶
   * @param {String} roomId 房间ID
   * @returns {Promise} 操作结果
   */
  async pinRoom(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/pin`,
        method: 'POST'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 取消房间置顶
   * @param {String} roomId 房间ID
   * @returns {Promise} 操作结果
   */
  async unpinRoom(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/pin`,
        method: 'DELETE'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 更新房间设置
   * @param {String} roomId 房间ID
   * @param {Object} settings 房间设置
   * @returns {Promise} 更新结果
   */
  async updateRoomSettings(roomId, settings) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/settings`,
        method: 'PUT',
        data: { settings }
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 关闭房间
   * @param {String} roomId 房间ID
   * @returns {Promise} 关闭结果
   */
  async closeRoom(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}`,
        method: 'DELETE'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  // ==================== 菜单管理接口 ====================

  /**
   * 获取房间菜单
   * @param {String} roomId 房间ID
   * @returns {Promise} 菜单数据
   */
  async getRoomMenu(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/menu`,
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 搜索菜品
   * @param {String} roomId 房间ID
   * @param {String} keyword 搜索关键词
   * @param {String} category 分类筛选
   * @returns {Promise} 搜索结果
   */
  async searchDishes(roomId, keyword, category = '') {
    try {
      const params = new URLSearchParams();
      params.append('keyword', keyword);
      if (category) {
        params.append('category', category);
      }

      const response = await this.request({
        url: `/rooms/${roomId}/menu/search?${params.toString()}`,
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取菜单模板列表
   * @returns {Promise} 模板列表
   */
  async getMenuTemplates() {
    try {
      const response = await this.request({
        url: '/menu-templates',
        method: 'GET'
      });

      return response.data.templates;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取菜单模板详情
   * @param {Number} templateId 模板ID
   * @returns {Promise} 模板详情
   */
  async getMenuTemplateDetail(templateId) {
    try {
      const response = await this.request({
        url: `/menu-templates/${templateId}`,
        method: 'GET'
      });

      return response.data.template;
    } catch (error) {
      throw error;
    }
  }

  // ==================== 订单管理接口 ====================

  /**
   * 提交订单
   * @param {Object} orderData 订单数据
   * @param {Object} options 请求选项
   * @returns {Promise} 订单信息
   */
  async submitOrder(orderData, options = {}) {
    try {
      // 使用完整的URL路径
      const fullUrl = this.baseURL + '/orders';
      
      // 添加调试信息
      console.log('提交订单请求:', {
        url: fullUrl,
        data: orderData,
        token: this.getToken() ? '有token' : '无token'
      });
      
      return new Promise((resolve, reject) => {
        wx.request({
          url: fullUrl,
          method: 'POST',
          data: orderData,
          header: {
            'Content-Type': 'application/json',
            'Authorization': this.getToken() ? `Bearer ${this.getToken()}` : '',
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'X-Requested-With': 'XMLHttpRequest'
          },
          timeout: this.timeout,
          enableHttp2: false,
          enableQuic: false,
          success: (res) => {
            console.log('订单提交响应:', res);
            console.log('响应数据:', res.data);
            
            // 检查是否有有效的响应数据（即使HTTP状态码不是200-299）
            if (res.data && typeof res.data === 'object') {
              if (res.data.code === 200 || res.data.code === 201) {
                console.log('订单提交成功，返回数据:', res.data.data);
                resolve(res.data.data.order || res.data.data);
              } else {
                console.log('订单提交失败，业务错误:', res.data);
                reject(res.data);
              }
            } else if (res.statusCode >= 200 && res.statusCode < 300) {
              // 如果没有业务错误码，但HTTP状态码正常，也认为成功
              console.log('订单提交成功（无业务错误码）');
              resolve(res.data);
            } else {
              console.log('HTTP状态码错误:', res.statusCode);
              reject(res);
            }
          },
          fail: (error) => {
            console.error('订单提交网络错误:', error);
            reject(error);
          }
        });
      });
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取我的订单
   * @returns {Promise} 订单列表
   */
  async getMyOrders() {
    try {
      const response = await this.request({
        url: '/orders/my',
        method: 'GET'
      });

      return response.data.orders;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取订单详情
   * @param {string} orderId 订单ID
   * @returns {Promise} 订单详情
   */
  async getOrderDetail(orderId) {
    try {
      const response = await this.request({
        url: `/orders/${orderId}`,
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取房间订单
   * @param {String} roomId 房间ID
   * @returns {Promise} 订单列表
   */
  async getRoomOrders(roomId) {
    try {
      const response = await this.request({
        url: `/rooms/${roomId}/orders`,
        method: 'GET'
      });

      return response.data.orders;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 取消订单
   * @param {Number} orderId 订单ID
   * @returns {Promise} 取消结果
   */
  async cancelOrder(orderId) {
    try {
      const response = await this.request({
        url: `/orders/${orderId}`,
        method: 'DELETE'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 确认订单
   * @param {Number} orderId 订单ID
   * @returns {Promise} 确认结果
   */
  async confirmOrder(orderId) {
    try {
      const response = await this.request({
        url: `/orders/${orderId}/confirm`,
        method: 'POST'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取订单统计
   * @param {String} roomId 房间ID
   * @returns {Promise} 统计信息
   */
  async getOrderStats(roomId) {
    try {
      const response = await this.request({
        url: `/orders/${roomId}/stats`,
        method: 'GET'
      });

      return response.data.stats;
    } catch (error) {
      throw error;
    }
  }

  // ==================== 性能监控接口 ====================

  /**
   * 获取系统指标
   * @returns {Promise} 系统指标
   */
  async getSystemMetrics() {
    try {
      const response = await this.request({
        url: '/performance/system',
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取数据库指标
   * @returns {Promise} 数据库指标
   */
  async getDatabaseMetrics() {
    try {
      const response = await this.request({
        url: '/performance/database',
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取缓存指标
   * @returns {Promise} 缓存指标
   */
  async getCacheMetrics() {
    try {
      const response = await this.request({
        url: '/performance/cache',
        method: 'GET'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 清除缓存
   * @returns {Promise} 清除结果
   */
  async clearCache() {
    try {
      const response = await this.request({
        url: '/performance/clear-cache',
        method: 'POST'
      });

      return response.data;
    } catch (error) {
      throw error;
    }
  }
}

// 创建单例实例
const apiService = new ApiService();

module.exports = apiService;
